package net.osc.support.http;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.osc.util.IOUtils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * @author <a href="mailto:wu.peng@ustcinfo.com">wu.peng</a>
 * 
 */
public class ResourcesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Log logger = LogFactory.getLog(ResourcesServlet.class);
	private final static String RESOURCE_PATH = "net/osc/resources";

	private String[] byteSuffixs = new String[] { ".jpg", ".png", ".gif", ".swf", ".psd" };
	private String encode = "utf-8";

	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding(encode);
		if (returnWebResourceFile(request, response)
				|| returnClassPathResourceFile(request, response)) {
			return;
		}
		response.sendError(HttpServletResponse.SC_NOT_FOUND);
	}

	private boolean returnWebResourceFile(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String contextPath = request.getContextPath();
		String requestURI = request.getRequestURI();
		if (contextPath == null) { // root context
			contextPath = "";
		}
		String webFileName = requestURI.substring(contextPath.length());

		InputStream in = this.getServletContext().getResourceAsStream(webFileName);
		try {
			if (in != null) {
				// 二进制资源
				for (String byteSuffix : byteSuffixs) {
					if (webFileName.endsWith(byteSuffix)) {
						response.getOutputStream().write(IOUtils.readByteArray(in));
						return true;
					}
				}
				// 文本资源
				if (webFileName.endsWith(".css")) {
					response.setContentType("text/css;charset=" + encode);
				} else if (webFileName.endsWith(".js")) {
					response.setContentType("text/javascript;charset=" + encode);
				}
				response.getWriter().write(IOUtils.read(in, encode));
				return true;
			}
		} finally {
			IOUtils.close(in);
		}
		return false;
	}

	private boolean returnClassPathResourceFile(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String contextPath = request.getContextPath();
		String servletPath = request.getServletPath();
		String requestURI = request.getRequestURI();
		if (contextPath == null) { // root context
			contextPath = "";
		}
		String classPathFileName = requestURI
				.substring(contextPath.length() + servletPath.length());
		classPathFileName = RESOURCE_PATH + classPathFileName;

		// 二进制资源
		for (String byteSuffix : byteSuffixs) {
			if (classPathFileName.endsWith(byteSuffix)) {
				byte[] bytes = IOUtils.readByteArrayFromResource(classPathFileName);
				if (bytes != null) {
					response.getOutputStream().write(bytes);
					return true;
				}
			}
		}
		// 文本资源
		String text = IOUtils.readFromResource(classPathFileName, encode);
		if (text != null) {
			if (classPathFileName.endsWith(".css")) {
				response.setContentType("text/css;charset=" + encode);
			} else if (classPathFileName.endsWith(".js")) {
				response.setContentType("text/javascript;charset=" + encode);
			}
			response.getWriter().write(text);
			return true;
		}
		logger.warn("web file and class path file both not found");
		logger.warn("web file name [" + requestURI.substring(contextPath.length()) + "]");
		logger.warn("class path file name [" + classPathFileName + "]");
		logger.warn("context path [" + contextPath + "]");
		logger.warn("servlet path [" + servletPath + "]");
		logger.warn("request URI [" + requestURI + "]");
		return false;
	}

}
